import asyncHandler from "express-async-handler"
import Product from "../models/product.js"

/**
 * 请求所有产品信息
 * @router GET /api/products
 * @access public
 */
export const getProducts = asyncHandler(async (req, res) => {
  const {pageNum=1, pageSize=10} = req.query

  const products = await Product.find({})
    .sort({
      updatedAt: 'desc'
    })
    .skip((pageNum-1)*pageSize)
    .limit(pageSize)
  const total = await Product.count({})
  res.json({
    success: true,
    msg: '',
    total,
    data: {
      total: await Product.count(),
      pageNum: pageNum,
      pageSize: pageSize,
      products
    }
  })
})

/**
 * 添加产品
 * @router POST /api/products
 * @access admin
 */
export const createProduct = asyncHandler(async (req, res) => {
  const product = new Product({
    name: '新品名',
    price: 0,
    description: '描述信息',
    image: '/imgs/sample.jpg',
    brand: '品牌',
    category: '类别',
    countInStock: 0,
    rating: 0,
    userId: req.user._id
  })  
  const createdProduct = await product.save()
  res.json({
    success: true,
    msg: '',
    data: createdProduct
  })
})

/**
 * 请求单个产品信息
 * @router GET /api/products/:id
 * @access public
 */
 export const getProductById = asyncHandler(async (req, res) => {
  try {
    const product = await Product.findById(req.params.id)
    res.json({
      success: true,
      msg: '',
      data: product
    })
  } catch (error) {
    res.status(500)
    throw new Error("商品不存在")
  }
})

/**
 * 删除产品
 * @router DELETE /api/products/:id
 * @access admin
 */
export const delProductById = asyncHandler(async (req, res) => {
  try {
    const product = await Product.findById(req.params.id)
    await product.remove()
    res.json({
      success: true,
      msg: '',
      data: null
    })
  } catch (error) {
    res.status(500)
    throw new Error("商品不存在")
  }
})

/**
 * 更新产品
 * @router PUT /api/products/:id
 * @access admin
 */
export const updateProductById = asyncHandler(async (req, res) => {
  try {
    const product = await Product.findById(req.params.id)
    for(const key in req.body) {
      product[key] = req.body[key]
    }
    await product.save()
    res.json({
      success: true,
      msg: '',
      data: product
    })
  } catch (error) {
    res.status(500)
    throw new Error("商品更新失败")
  }
})